/*
 * Antonio Canabrava Fraideinberze 7152292
 * Lucas Avelino Sodre Santos      7239086
 * Pedro Rael Garcia               7153021
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <omp.h>
#include "avl.h"

int
palindrome(char *word)
{
    int i;
    int res = 0;
    int len = strlen(word);

    for(i = 0; i < len; i++)
        if(word[i] == word[len - i - 1])
            res++;

    if(res==len)
        return 1;

    else
        return 0;
}


int main()
{
    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;
    int i;
    char *pch;
    pFile = fopen("shakespe.txt" , "rb");

    if(pFile==NULL)
    {
        fputs("File error",stderr);
        exit(1);
    }

    // obtain file size:
    fseek(pFile , 0 , SEEK_END);
    lSize = ftell(pFile);
    rewind(pFile);
    // allocate memory to contain the whole file:
    buffer = (char*) malloc(sizeof(char)*lSize);

    if(buffer == NULL)
    {
        fputs("Memory error",stderr);
        exit(2);
    }

    // copy the file into the buffer:
    result = fread(buffer,1,lSize,pFile);

    if(result != lSize)
    {
        fputs("Reading error",stderr);
        exit(3);
    }

    /* the whole file is now loaded in the memory buffer. */
    // terminate
    fclose(pFile);
    size_t b = strlen(buffer);

    for(i=0; i < b ; i++)
    {
        buffer[i] = tolower(buffer[i]);

        if(ispunct(buffer[i]) || isspace(buffer[i]))
            buffer[i]='\n';
    }

    node *words = NULL;
    pFile = fopen("res.txt" , "w");
    pch = strtok(buffer,"\n");

    while(pch != NULL)
    {
        if(find(pch,words)== NULL && palindrome(pch))
        {
            words = insert(pch,words);
            fprintf(pFile,"%s\n",pch);
        }

        pch = strtok(NULL,"\n");
    }

    free(buffer);
    fclose(pFile);
    return 0;
}
